package com.tj.jinzao.activity;


import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.nim.uikit.video.jzvd.Jzvd;
import com.tandong.bottomview.view.BottomView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tj.jinzao.App;
import com.tj.jinzao.R;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.fragment.ArticleDetailListFragment;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.ReportBean;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Util;
import com.tj.jinzao.widgets.CommentDialog;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


/**
 * 话题，日记，详情页面
 * Created by wjy on 2019/1/5.
 */
public class ArticleDetailActivity extends BaseActivity {
    private BottomView bottomView;

    @Override
    public int getLayoutResource() {
        return R.layout.base_activity_fragment_dea_layout;
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }
    Article article;
    @Override
    protected void setupView() {
        super.setupView();
        api = WXAPIFactory.createWXAPI(this, Constant.WX_APPID);
        api.registerApp(Constant.WX_APPID);
        getImageUrl();
        TextView toolbar_title= findViewById(R.id.toolbar_title);
        article = (Article) getIntent().getSerializableExtra("article");
        toolbar_title.setText(article.getType() == 1 ? "健康日记" : article.getTitle());
        findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopWindow();
            }
        });
        findViewById(R.id.back_lay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    private byte[] bytes;
    /**
     * 得到文件流
     * @param url
     * @return
     */
    public static byte[] getFileStream(String url){
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private IWXAPI api;

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }


    private void showPopWindow(){
        bottomView=new BottomView(ArticleDetailActivity.this, R.style.BottomViewTheme_Defalut, R.layout.share_item);
        bottomView.setAnimation(R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView exit=bottomView.getView().findViewById(R.id.exit);
        LinearLayout lay_1=bottomView.getView().findViewById(R.id.lay_1);
        LinearLayout lay_2=bottomView.getView().findViewById(R.id.lay_2);
        LinearLayout lay_3=bottomView.getView().findViewById(R.id.lay_3);
        LinearLayout lay_4=bottomView.getView().findViewById(R.id.lay_4);
        LinearLayout lay_5=bottomView.getView().findViewById(R.id.lay_5);
        LinearLayout lay_6=bottomView.getView().findViewById(R.id.lay_6);
        lay_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(imageUrl==null||imageUrl.equals("")){
                    ToastUtils.showToast(ArticleDetailActivity.this,"图片资源获取失败");
                }
                App.isShare=true;
                WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
                miniProgramObj.webpageUrl = "https://nian.im/early/share.html"; // 兼容低版本的网页链接
                miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
                miniProgramObj.userName = "gh_fd3ac0efa79b";     // 小程序原始id
                if(!article.isVideo()){
                    miniProgramObj.path="/pages/circle/show?id="+article.getId()+"&sid="+UserManager.getInstance().getUser().getId();
                }else {
                    miniProgramObj.path="/pages/circle/videoshow?id="+article.getId()+"&sid="+UserManager.getInstance().getUser().getId();
                }
//                /pages/circle/index  //社区首页地址
//                miniProgramObj.path = "/pages/index";            //小程序页面路径
                WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                msg.title = "尽早";                    // 小程序消息title
                msg.description = "尽早小程序";               // 小程序消息desc
//                Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.ic_camera);
                msg.thumbData = bytes;

//                msg.thumbData = bytes;                      // 小程序消息封面图片，小于128k
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("miniProgram");
                req.message = msg;
                req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
                api.sendReq(req);
                bottomView.dismissBottomView();
            }
        });
        lay_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(ArticleDetailActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.showToast(ArticleDetailActivity.this,"此功能暂未开放");
                bottomView.dismissBottomView();
            }
        });
        lay_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Util.shareWeb(ArticleDetailActivity.this,api,SendMessageToWX.Req.WXSceneTimeline);
                bottomView.dismissBottomView();
            }
        });
        lay_5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               getInterest();
               bottomView.dismissBottomView();
            }
        });
        lay_6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommentDialog dialog = new CommentDialog(ArticleDetailActivity.this);
                dialog.setSendListener(new CommentDialog.OnSendListener() {
                    @Override
                    public void send(String content, int id) {
                        getReport(content);
                    }
                });
                dialog.setHint("举报", 1);
                dialog.show();
                bottomView.dismissBottomView();
            }
        });
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
            }
        });

    }

    private void getReport(String content){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("uid",String.valueOf(UserManager.getInstance().getUser().getId()));
        hashMap.put("reportedUid",String.valueOf(article.getUser().getId()));
        hashMap.put("content",content);
        if(article.getType()==1){
            hashMap.put("type","1");
        }else {
            hashMap.put("type","2");
        }
        addSubscription(mApiService.getReport(hashMap), new SubscriberCallBack<ReportBean>(this) {
            @Override
            protected void onSuccess(ReportBean list) {
                ToastUtils.showToast(ArticleDetailActivity.this,"举报成功");
            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }
    private void getInterest(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("uid",String.valueOf(UserManager.getInstance().getUser().getId()));
        hashMap.put("content","不感兴趣");
        if(article.getType()==1){
            hashMap.put("type","rj");
        }else {
            hashMap.put("type","ht");
        }
        hashMap.put("externalId",article.getId());
        addSubscription(mApiService.getInterest(hashMap), new SubscriberCallBack<ReportBean>(this) {
            @Override
            protected void onSuccess(ReportBean list) {
               ToastUtils.showToast(ArticleDetailActivity.this,"已为您添加至不感兴趣");

            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;
    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    public void detachView() {
        onUnsubscribe();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
        App.isShare=false;
    }

    private String imageUrl;
    private void getImageUrl(){
        addSubscription(mApiService.getWXImageUrl(), new SubscriberCallBack<String>(this) {
            @Override
            protected void onSuccess(String list) {
                imageUrl= Constant.IMAGE_PREFIX+list;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        bytes= getFileStream(imageUrl);
                    }
                }).start();
            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }

    @Override
    protected Fragment createFragment() {
        Article article = (Article) getIntent().getSerializableExtra("article");
        return ArticleDetailListFragment.newInstance(article);
    }
    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.resetAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

}
